package idv.cjcat.pyronova.utils {
	import flash.display.BitmapData;
	
	public class GraphicsUtils {
		
		public static function drawLineSegments(points:Vector.<int>, colors:Vector.<uint>, useAlpha:Boolean, target:BitmapData):void {
			for (var i:int = 0, j:int = 0, len:int = points.length; i < len; ++j) {
				drawLine(
					points[i++], 
					points[i++], 
					points[i++], 
					points[i++], 
					colors[j], 
					useAlpha, 
					target
				);
			}
		}
		
		public static function drawLines(points:Vector.<int>, colors:Vector.<uint>, useAlpha:Boolean, target:BitmapData):void {
			for (var i:int = 0, j:int = 0, len:int = points.length - 2; i < len; ++j) {
				drawLine(
					points[i++], 
					points[i++], 
					points[i], 
					points[i + 1], 
					colors[j], 
					useAlpha, 
					target
				);
			}
		}
		
		/**
		 * Bresenham's line algorithm
		 * http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
		 */
		public static function drawLine(x0:int, y0:int, x1:int, y1:int, color:uint, useAlpha:Boolean, target:BitmapData):void {
			var dx:int = x1 - x0;
			var dy:int = y1 - y0;
			var sx:int = (dx >= 0)?(1):(-1);
			var sy:int = (dy >= 0)?(1):( -1);
			dx = (dx >= 0)?(dx):(-dx);
			dy = (dy >= 0)?(dy):(-dy);
			var err:int = dx - dy, e2:int;
			
			if (!useAlpha) color |= 0xFF000000
			while (true) {
				target.setPixel32(x0, y0, color);
				
				if ((x0 == x1) && (y0 == y1)) break;
				
				e2 = err << 1;
				if (e2 > -dy) {
					err -= dy;
					x0 += sx;
				}
				if (e2 < dx) {
					err += dx;
					y0 += sy;
				}
			}
		}
		
		public static function drawCircle(cx:int, cy:int, radius:Number, color:uint, useAlpha:Boolean, target:BitmapData):void {
			var r:int = int(radius + 0.5);
			var error:int = -r;
			var x:int = r;
			var y:int = 0;
			
			if (!useAlpha) color |= 0xFF000000
			while (x >= y) {
				target.setPixel32(cx + x, cy + y, color);
				if (x != 0) target.setPixel32(cx - x, cy + y, color);
				if (y != 0) target.setPixel32(cx + x, cy - y, color);
				if (x != 0 && y != 0) target.setPixel32(cx - x, cy - y, color);
				if (x != y) {
					target.setPixel32(cx + y, cy + x, color);
					if (y != 0) target.setPixel32(cx - y, cy + x, color);
					if (x != 0) target.setPixel32(cx + y, cy - x, color);
					if (y != 0 && x != 0) target.setPixel32(cx - y, cy - x, color);
				}
				
				error += y;
				++y;
				error += y;
				if (error >= 0) {
					--x;
					error -= x;
					error -= x;
				}
			}
		}
	}
}